﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Core.Interfaces;
using Core.Interfaces.IDAO;
using Core.Unity;
using Microsoft.Practices.Unity;
namespace Core.DAO
{
    class PrivatePersonDAO : AbstractDAO<IPrivatePerson>, IPrivatePersonDAO
    {
        public PrivatePersonDAO(IConnection connection) : base(connection)
        {
        }

        #region Overrides of AbstractDAO

       
        

        #endregion


        public override List<IPrivatePerson> GetAll(bool is_lasy = false)
        {
            var result = new List<IPrivatePerson>();
            var query =
                Connection.ExecuteSelectQuery(
                    "select c.adress,c.telephone,c.customer_id, p.fio,p.pasport from customer c LEFT  JOIN private_person p ON (p.customer_id = c.customer_id) ",
                    7);
            foreach (object[] objectse in query)
            {
                var district = ResolverContainer.Resolver.Resolve<IPrivatePerson>();
                district.Address = objectse[0].ToString();
                district.Telephone = objectse[1].ToString();
                district.CustomerID = int.Parse(objectse[2].ToString());
                district.Fio = objectse[3].ToString();
                district.PasportNumber = objectse[4].ToString();
                district.ConstructIt(null);
                if (is_lasy)
                {
                    GetDependendModels(district, objectse);
                }
                result.Add(district);
            }
            return result;
        }

        protected override void GetDependendModels(object domainobject, object[] row)
        {
            throw new NotImplementedException();
        }

        public override bool SaveOrUpdateAndCommit(IDomainObject domainObject)
        {
            bool result = false;
            var pp = (IPrivatePerson) domainObject;
            try
            {
                if (domainObject.FromDatabase())
                {
                    Connection.ExecuteQuery(string.Format("update customer SET adress='{0}',telephon e='{1}' where customer_id = {2}",new object[]{pp.Address,pp.Telephone,pp.CustomerID}));
                }
                else
                {
                    Connection.ExecuteQuery(string.Format("insert into private_person (`fio`, `pasport`, `customer_id`) VALUES ('{0}','{1}')", new object[] { pp.Fio, pp.PasportNumber }));
                }
                result = true;
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error,
                                MessageBoxDefaultButton.Button1);
                Connection.CloseConnection();

            }
            return result;
        }
    }
}
